using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 游戏物体类型的工厂基类
/// </summary>
public class BaseFactory : IBaseFactory
{
    //当前拥有的gameobject类型的资源（UI，UIPanel，GameObject）
    protected Dictionary<string, GameObject> factoryDict = new Dictionary<string, GameObject>();

    //对象池字典
    protected Dictionary<string, Stack<GameObject>> ObjectPoolDict = new Dictionary<string, Stack<GameObject>>();
    //加载路径
    protected string loadPath;
    public BaseFactory()
    {
        loadPath = "Prefabs/";
    }

    //放入池子
    public void PushItem(string itemName, GameObject item)
    {
        item.SetActive(false);
        item.transform.SetParent(GameManager.Instance.transform);
        if (ObjectPoolDict.ContainsKey(itemName))
        {
            ObjectPoolDict[itemName].Push(item);
        }
        else
        {
            Debug.Log("当前字典没有" + itemName + "的栈");
        }
    }

    //取实例
    public GameObject GetItem(string itemName)
    {
        GameObject itemGo = null;
        if (ObjectPoolDict.ContainsKey(itemName))
        {
            if (ObjectPoolDict[itemName].Count == 0)
            {
                GameObject go = GetResource(itemName);
                itemGo = GameManager.Instance.CreateItem(go);
            }
            else
            {
                itemGo = ObjectPoolDict[itemName].Pop();
                itemGo.SetActive(true);
            }
        }
        else
        {
            ObjectPoolDict.Add(itemName, new Stack<GameObject>());
            GameObject go = GetResource(itemName);
            itemGo = GameManager.Instance.CreateItem(go);
        }
        if (itemGo == null)
        {
            Debug.Log(itemName + "实例获取失败");
        }
        return itemGo;
    }

    //取资源的方法
    private GameObject GetResource(string itemName)
    {
        GameObject itemGo = null;
        string itemLoadPath = loadPath + itemName;
        if (factoryDict.ContainsKey(itemName))
        {
            itemGo = factoryDict[itemName];
        }
        else
        {
            itemGo = Resources.Load<GameObject>(itemLoadPath);
            factoryDict.Add(itemName, itemGo);
        }
        if (itemGo == null)
        {
            Debug.Log(itemName + "加载资源失败：" + "失败路径" + itemLoadPath);
        }


        return itemGo;
    }

}
